package com.smart.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.smart.entity.Result;
import com.smart.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getMethod().equals("OPTIONS")){
            // 在拦截器中设置允许跨域
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Headers","*");
            response.setHeader("Access-Control-Allow-Methods","*");
            response.setHeader("Access-Control-Allow-Credentials","true");
            response.setHeader("Access-Control-Max-Age","3600");
            return true;
        }
        HttpSession session = request.getSession();
        if (session.getAttribute("claims") != null) {
            // System.out.println("Session中有claims, 放行...");
            return true;
        }

        String token = request.getHeader("Authorization");
        Claims claims = null;
        try {
            claims = JwtUtils.parseJWT(token);
            session.setAttribute("claims", claims);
            // System.out.println("Session中已储存claims, 放行...");
            return true;
        } catch (Exception e) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            ObjectMapper mapper = new ObjectMapper();
            try {
                response.getWriter().write(mapper.writeValueAsString(Result.error("您的登陆信息已过期，请重新登录。")));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return false;
        }
    }
}